<template>
    <view class="flex flex-column main-container">
        <u--text :lines="1" color="black" size="25" text="为你推荐" class="recommend-title"></u--text>
        <!-- 推荐帖子列表 -->
        <view class="flex flex-row recommend-posts-container">
            <scroll-view scroll-x="true" style="white-space: nowrap; padding: 10px;">
                <view class="background recommended-post-item" v-for="(post, index) in recommendedPosts" :key="index" @click="goToPostDetail(post.postId)">
                    <!-- 第一部分：推荐数据的第一张图片 -->
                    <image :src="post.firstImage" mode="scaleToFill" style="width: 100%; height: 80px;"></image>
                    <!-- 第二部分：标题 -->
                    <view class="flex-column post-content" style="padding: 10px;">
                        <u--text :lines="1" color="black" size="18" :text="post.title" style="font-weight: bold;"></u--text>
                    </view>
                </view>
            </scroll-view>
        </view>
        <!-- 帖子列表 -->
        <view style="width: 100%;">
            <view  v-for="(post, index) in postList" :key="index" @click="goToPostDetail(post.postId)">	
                <view style="background-color: white;width: 100%;padding: 20px;margin-bottom: 20px;border-radius: 3px;">
                    <!-- 第一部分：头像和用户名 -->
                    <view class="flex flex-row">
                        <u-avatar :src="post.avatarUrl" shape="circle" size="50" mode="scaleToFill"></u-avatar>
                        <view class="flex-column" style="margin-left: 10px;">
                            <u--text :lines="1" color="rgba(0, 0, 0, .9)" block="true" size="23" :text="post.username"></u--text>
                             <u--text :lines="1" color="rgba(0, 0, 0, .6)" :text="formatCreatedAt(post.createdAt)"></u--text>
                        </view>
                        
                    </view>
                    <!-- 第二部分：标题或内容、发布时间、图片 -->
                    <view style="margin-top: 10px;">
                        <view style="margin-right: 20px;">
                             <u--text :lines="2" color="black" size="18" lineHeight="28px" :text="post.content || post.title"></u--text>
                        </view>
                       
                        <view class="flex flex-wrap" style="margin-top: 10px;">
                            <image v-for="(image, imgIndex) in post.images" :key="imgIndex"
                                   style="width: calc(33.33% - 10px); height: 120px;margin-top: 2px;"
                                   mode="scaleToFill" :src="image"></image>
                        </view>
                    </view>
                    <view class="flex" style="margin-top: 8px;">
                        <u-tag :text="post.location" size="mini" icon="map" plain shape="circle"></u-tag>
                    </view>
                    <!-- 第三部分：功能栏（评论和点赞） -->
                    <view class="flex flex-row justify-between margin-top">
                        <u-icon name="more-circle" color="grey" :label='post.commentCount' size="28"></u-icon>
                        <view style="margin-right: 50px;">
                            <u-icon name="heart"  color="grey" :label='post.likeCount' size="28"></u-icon>
                        </view>
                        
                    </view>
                </view>
            </view>
        </view>
        <!-- 发布帖子按钮 -->
        <view class="fix-button" @click="toLink">
            <u-button type="primary" shape="circle" :plain="true" :hairline="true" text="发布"></u-button>
        </view>
    </view>
</template>

<script>
    import moment from 'moment';
export default {
    data() {
        return {
            list2: [
                "https://images.pexels.com/photos/869258/pexels-photo-869258.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
                "https://images.pexels.com/photos/9754/mountains-clouds-forest-fog.jpg?auto=compress&cs=tinysrgb&w=600",
                "https://images.pexels.com/photos/627654/pexels-photo-627654.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load",
                "https://images.pexels.com/photos/113338/pexels-photo-113338.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
                "https://images.pexels.com/photos/804565/pexels-photo-804565.jpeg?auto=compress&cs=tinysrgb&w=600",
            ],
            postList: [],
            userId: null,
            lableList: [
                {
                    id: 1,
                    name: '热门徒步路线',
                    icon: '/static/luxian.png',
                    type: 'hiking'
                },
                {
                    id: 2,
                    name: '户外安全',
                    icon: '/static/hiking.png',
                    type: 'safety'
                },
                {
                    id: 3,
                    name: '活动',
                    icon: '/static/activity.png',
                    type: 'activity'
                },
                {
                    id: 4,
                    name: '约伴',
                    icon: '/static/invention.png',
                    type: 'partner'
                }
            ],
            recommendedPosts: [] // 添加推荐帖子列表
        };
    },
    onLoad() {
        this.userId = uni.getStorageSync('userInfo')?.userId || null;
        this.getPostList();
        this.getRecommendations(); // 调用获取推荐数据的方法
    },
    methods: {
        goToRoute(type) {
            uni.navigateTo({
                url: `/pages/index/route/route?type=${type}`
            });
        },
        getPostList() {
            uni.request({
                url: 'http://localhost:8090/post',
                method: 'GET',
                success: (res) => {
                    if (res.data.code === 200) {
                        // console.log(res.data.data)
                        this.postList = res.data.data.map(post => {
                            const images = post.imageUrls ? post.imageUrls.split(',') : [];
                            const imageUrls = images.map(img => `http://localhost:8090/file/user/${post.userId}/posts/${img}`);
                            return {
                                ...post,
                                images: imageUrls
                            };
                        });
                    } else {
                        uni.showToast({
                            title: '获取帖子列表失败',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: '请求失败：' + error.errMsg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },
        goToPostDetail(postId) {
            uni.navigateTo({
                url: `/pages/index/postDetail?postId=${postId}&userId=${this.userId}`
            });
        },
        toLink() {
            if (!this.userId) {
                uni.showToast({
                    title: '请先去登录',
                    icon: 'fail',
                    duration: 1500
                });
                uni.navigateTo({
                    url: '/pages/my/wxLogin'
                });
            } else {
                uni.navigateTo({
                    url: '/pages/index/addPost'
                });
            }
        },
        getRecommendations() {
            uni.request({
                url: `http://localhost:8090/recommend/${this.userId}`, // 推荐接口路径
                method: 'GET',
                success: (res) => {
                    console.log('用户推荐数据', res.data)
                    if (res.statusCode === 200) {
                        this.recommendedPosts = res.data.map(post => {
                            const images = post.imageUrls ? post.imageUrls.split(',') : [];
                            const firstImage = images.length > 0 ?
                                `http://localhost:8090/file/user/${post.userId}/posts/${images[0]}` :
                                '';
                            return {
                                ...post,
                                firstImage
                            };
                        });
                    } else {
                        uni.showToast({
                            title: '获取推荐数据失败',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: '请求推荐数据失败：' + error.errMsg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },
        formatCreatedAt(time) {
            return time ? moment(time).format('YYYY-MM-DD') : '';
        },
    }
};
</script>

<style>
.recommend-title {
    margin-bottom: 10px;
}

.recommend-posts-container {
    margin-bottom: 20px;
}

.recommended-post-item {
    display: inline-block;
    width: 180px;
    margin-right: 10px;
    height: 120px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    overflow: hidden;
}

.post-list-container {
    margin-bottom: 20px;
    background-color: white;
}

.post-item {
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
}

.post-header {
    margin-bottom: 10px;
}

.post-body {
    margin-bottom: 10px;
}

.post-footer {
    margin-top: 10px;
}

.fix-button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    display: flex;
}
</style>